package xyz.zdsoft.homework_manage_module.Service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.zdsoft.common.entity.*;
import xyz.zdsoft.common.service.*;
import xyz.zdsoft.common.utils.JwtUtils;
import xyz.zdsoft.common.utils.Result;
import xyz.zdsoft.homework_manage_module.mapper.TeacherTaskMapper;
import xyz.zdsoft.homework_manage_module.Service.TeacherTaskService;
import xyz.zdsoft.homework_manage_module.bo.NewJob;
import xyz.zdsoft.homework_manage_module.bo.QueryJob;
import xyz.zdsoft.homework_manage_module.vo.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TeacherTaskServiceImpl implements TeacherTaskService {
    @Autowired
    HttpServletRequest request;
    @Autowired
    IWorkInfoService iWorkInfoService;
    @Autowired
    IWorkSubmitInfoService iWorkSubmitInfoService;
    @Autowired
    ITeamMemberInfoService iTeamMemberInfoService;
    @Autowired
    IComprehensiveScoreService iComprehensiveScoreService;
    @Autowired
    ISysUserService iSysUserService;
    @Autowired
    ICourseInfoService iCourseInfoService;
    @Autowired
    TeacherTaskMapper teacherTaskMapper;
    /*新增作业*/
    @Override
    public Result NewJob(NewJob newJob) {
        boolean x;
        String s="";
        Result result=null;
        String teacher_id= JwtUtils.getMemberIdByJwtToken(request);//获取教师id
        WorkSubmitInfo workSubmitInfo = null;//作业管理表
        if (newJob.getTeamInfoId()==null && newJob.getTeamInfoId().size()>0){
            return Result.error().message("请选择小组");
        }
        if (newJob.getWorkType()==null||newJob.getWorkType()==""){
            return Result.error().message("请选择类型");
        }
        if (newJob.getCompleteDate()==null){
            return Result.error().message("请输入计划完成时间");
        }
        if (newJob.getTitle()==null||newJob.getTitle()==""){
            return Result.error().message("请输入主题");
        }
        if (newJob.getCourseId()==null||newJob.getCourseId()<=0){
            return Result.error().message("请选择课程");
        }
        //加入作业表
        WorkInfo workInfo=new WorkInfo();;//创建作业表
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.parse(newJob.getCompleteDate(),df);
        workInfo.setTitle(newJob.getTitle());
        workInfo.setCompleteDate(ldt);
        workInfo.setAppendsLink(newJob.getAppendsLink());
        workInfo.setWorkType(newJob.getWorkType());
        workInfo.setCourseId(newJob.getCourseId());
        workInfo.setTeacherId(Integer.parseInt(teacher_id));
        x=iWorkInfoService.save(workInfo);//加入作业表
        //查询新增作业id
        QueryWrapper<WorkInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title",newJob.getTitle());
        queryWrapper.eq("complete_date",newJob.getCompleteDate());
        queryWrapper.eq("course_id",newJob.getCourseId());
        queryWrapper.eq("work_type",newJob.getWorkType());
        queryWrapper.eq("appends_link",newJob.getAppendsLink());
        queryWrapper.eq("teacher_id",Integer.parseInt(teacher_id));
        WorkInfo workInfo1=iWorkInfoService.getOne(queryWrapper);//查询新增的作业id
        if (x==true) {
            if (newJob.getWorkType().equals("0")) {// 判断是否个人作业
                workSubmitInfo = new WorkSubmitInfo();
                if (newJob.getStudentId() == null||(newJob.getStudentId()!=null&&newJob.getStudentId().size()==0)) {//判断是否选择学生
                    List<Long> longs = newJob.getTeamInfoId();//拿到小组所有id
                    for (int i = 0; i < longs.size(); i++) {
                        //拿到该小组下加入课程的所有学生
                        List<RestStudent> list =teacherTaskMapper.SelectStudents(workInfo1.getId().intValue(),longs.get(i).intValue());
                        if (list != null) {//判断该小组成员是否为空
                            for (int l = 0; l < list.size(); l++) {
                                workSubmitInfo.setStudentId(list.get(l).getStudentId());//注入学生id
                                workSubmitInfo.setTeamInfoId(longs.get(i));//注入小组id
                                workSubmitInfo.setWorkId(workInfo1.getId());//注入作业id
                                x=iWorkSubmitInfoService.save(workSubmitInfo);
                                if (x==true){
                                    s="新增成功";
                                }else {
                                    result= Result.error().message("请重新选择学生");
                                    return result;
                                }
                            }
                        } else {
                            result= Result.error().message("该小组没有成员");
                            return result;
                        }
                    }
                    result= Result.ok().message(s);//成功后返回结果
                }else {
                    List<Long> longs1=newJob.getStudentId();//拿到所有学生id
                    for (int i=0;i<longs1.size();i++){
                        QueryWrapper<TeamMemberInfo> queryWrapper1 = new QueryWrapper<>();
                        queryWrapper1.eq("student_id", longs1.get(i));
                        TeamMemberInfo teamMemberInfo=iTeamMemberInfoService.getOne(queryWrapper1);//查询学生所属小组
                        workSubmitInfo.setStudentId(longs1.get(i));//注入学生id
                        workSubmitInfo.setTeamInfoId(teamMemberInfo.getTeamInfoId());//注入小组id
                        workSubmitInfo.setWorkId(workInfo1.getId());//注入作业id
                        x=iWorkSubmitInfoService.save(workSubmitInfo);
                        if (x==true){
                            s="新增成功";
                        }else {
                            result= Result.error().message("请重新选择学生");
                            return result;
                        }
                    }
                    result= Result.ok().message(s);//成功后返回结果
                }
            } else if (newJob.getWorkType().equals("1")) {//判断是否是阶段性作业
                List<Long> longs2 = newJob.getTeamInfoId();//拿到小组所有id
                for (int i=0;i<longs2.size();i++){
                    QueryWrapper<TeamMemberInfo> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("team_info_id", longs2.get(i));
                    queryWrapper1.eq("is_team_leader","1");
                    TeamMemberInfo teamMemberInfo1=iTeamMemberInfoService.getOne(queryWrapper1);
                    if (teamMemberInfo1!=null){
                        workSubmitInfo=new WorkSubmitInfo();
                        workSubmitInfo.setStudentId(teamMemberInfo1.getStudentId());//注入学生id
                        workSubmitInfo.setTeamInfoId(teamMemberInfo1.getTeamInfoId());//注入小组id
                        workSubmitInfo.setWorkId(workInfo1.getId());//注入作业id
                        x=iWorkSubmitInfoService.save(workSubmitInfo);
                        if (x==true){
                            s="新增成功";
                        }else {
                            result= Result.error().message("请重新选择小组");
                            return result;
                        }
                    }else {
                        result= Result.error().message("没有组长");
                        return result;
                    }

                }
                result= Result.ok().message(s);//成功后返回结果

            } else {//判断是否为最终交付作业
                List<Long> longs3 = newJob.getTeamInfoId();//拿到小组所有id
                for (int i=0;i<longs3.size();i++){
                    QueryWrapper<TeamMemberInfo> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("team_info_id", longs3.get(i));
                    queryWrapper1.eq("is_team_leader","1");
                    TeamMemberInfo teamMemberInfo1=iTeamMemberInfoService.getOne(queryWrapper1);
                    if (teamMemberInfo1!=null){
                        workSubmitInfo=new WorkSubmitInfo();
                        workSubmitInfo.setStudentId(teamMemberInfo1.getStudentId());//注入学生id
                        workSubmitInfo.setTeamInfoId(teamMemberInfo1.getTeamInfoId());//注入小组id
                        workSubmitInfo.setWorkId(workInfo1.getId());//注入作业id
                        x=iWorkSubmitInfoService.save(workSubmitInfo);
                        if (x==true){
                            s="新增成功";
                        }else {
                            result= Result.error().message("请重新选择小组");
                            return result;
                        }
                    }else {
                        result= Result.error().message("没有组长");
                        return result;
                    }
                    //最终交付作业生成综合打分记录
                    ComprehensiveScore comprehensiveScore1=new ComprehensiveScore();
                    comprehensiveScore1.setTeamId(longs3.get(i).intValue());
                    comprehensiveScore1.setCourseId(newJob.getCourseId().intValue());
                    x=iComprehensiveScoreService.save(comprehensiveScore1);
                    if (x==true){
                        QueryWrapper<TeamMemberInfo> queryWrapper2 = new QueryWrapper<>();
                        queryWrapper2.eq("team_info_id", longs3.get(i));
                        List<TeamMemberInfo> list = iTeamMemberInfoService.list(queryWrapper2);//查询该小组下所有学生id
                        for (int l=0;l<list.size();l++){
                            ComprehensiveScore comprehensiveScore=new ComprehensiveScore();
                            comprehensiveScore.setStudentId(list.get(l).getStudentId().intValue());//注入学生
                            comprehensiveScore.setTeamId(longs3.get(i).intValue());
                            comprehensiveScore.setCourseId(newJob.getCourseId().intValue());
                            x=iComprehensiveScoreService.save(comprehensiveScore);
                            if (x==false){
                                result= Result.error().message("综合打分记录生成失败");
                                return result;
                            }
                        }
                    }else {
                        result= Result.error().message("综合打分记录生成失败");
                        return result;
                    }

                }
                result= Result.ok().message(s);//成功后返回结果

            }
        }else {
            result= Result.error().message("新增失败");
        }
        return result;
    }


    /*查询作业*/
    @Override
    public Result QueryJob(QueryJob queryJob) {
        String teacher_id= JwtUtils.getMemberIdByJwtToken(request);//获取教师id
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",teacher_id);
        String  teacherName=iSysUserService.getOne(queryWrapper).getName();
        if (queryJob.getCurrent()<=0||queryJob.getCurrent()==null){
            queryJob.setCurrent(1);
        }
        if (queryJob.getSize()<=0||queryJob.getSize()==null){
            queryJob.setSize(10);
        }
        Page page=PageHelper.startPage(queryJob.getCurrent(),queryJob.getSize(),"id  DESC");
        List<RestQueryJob> list=teacherTaskMapper.NewQueryJob(queryJob,teacherName);
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setPages(page.getPages());//总页数
        pageInfo.setTotal(page.getTotal());//总条数
        for (int i=0;i<list.size();i++){
            if(list.get(i).getWorkType().equals("0")){
                list.get(i).setWorkType("平时作业");
            }else if(list.get(i).getWorkType().equals("1")){
                list.get(i).setWorkType("阶段性作业");
            }else {
                list.get(i).setWorkType("最终交互作业");
            }
        }
        Map<String,Object> map1 = new HashMap<>();
        map1.put("page",page.getPages());
        map1.put("total",page.getTotal());
        map1.put("info",list);
        return Result.ok().data(map1);
    }
    /*查看作业*/
    @Override
    public Result<RestViewJob> ViewJob(Integer id) {
        RestViewJob restViewJob=new RestViewJob();
        QueryWrapper<WorkInfo> queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("id",id);
        WorkInfo workInfo=iWorkInfoService.getOne(queryWrapper);
        restViewJob.setAppendsLink(workInfo.getAppendsLink());
        restViewJob.setCompleteDate(workInfo.getCompleteDate());
        restViewJob.setTitle(workInfo.getTitle());
        if(workInfo.getWorkType().equals("0")){
            restViewJob.setWorkType("平时作业");
        }else if(workInfo.getWorkType().equals("1")){
            restViewJob.setWorkType("阶段性作业");
        }else {
            restViewJob.setWorkType("最终交互作业");
        }
        QueryWrapper<CourseInfo> queryWrapper1=new  QueryWrapper<>();
        queryWrapper1.eq("id",workInfo.getCourseId());
        CourseInfo courseInfo=iCourseInfoService.getOne(queryWrapper1);
        restViewJob.setCourseName(courseInfo.getCourseName());//注入课程名称
        restViewJob.setStudentName(teacherTaskMapper.NewQueryStuName(id));
        String s= teacherTaskMapper.NewQueryTeamName(id);
        String a[]=s.split(",");
        ArrayList b = new ArrayList();
        if (a!=null) {
            for (int i= 0; i<a.length;i++){
                b.add(a[i]);
            }
        }
        restViewJob.setTeamName(b);
        return Result.ok().data(restViewJob);
    }
    /*删除作业*/
    @Override
    public Result DeleteJob(Integer id) {
        boolean b=teacherTaskMapper.DeleteJob(id);
        if(b==false){
            return Result.error().message("删除失败");
        }else {
            return Result.ok().message("删除成功");
        }
    }

    /*选择课程*/
    @Override
    public Result SelectCourse() {
        String teacherId= JwtUtils.getMemberIdByJwtToken(request);//获取教师id
       List list= teacherTaskMapper.SelectCourse(Integer.parseInt(teacherId));
        return Result.ok().data(list) ;
    }
    /*选择类型*/
    @Override
    public Result<JobType> JobType(Integer id) {
        JobType jobType=null;
        //作业类型，参见WorkType枚举;0平时作业，1阶段性作业，2最终交互作业
        if (id==null ||id==0){
            return Result.error().message("请选择课程");
        }
        List<JobType> list1=new ArrayList<>();;
        String teacherId= JwtUtils.getMemberIdByJwtToken(request);//获取教师id
         List list =teacherTaskMapper.JobType(id,Integer.parseInt(teacherId));
         if (list==null){
             jobType=new JobType();
             jobType.setWorkType("0");
             jobType.setWorkTypeName("平时作业");
             list1.add(jobType);
         } else {
             for (int i=0;i<3;i++){
                 jobType=new JobType();
                 jobType.setWorkType(String.valueOf(i));
                 if(i==0){
                     jobType.setWorkTypeName("平时作业");
                 }else if(i==1){
                     jobType.setWorkTypeName("阶段性作业");
                 }else {
                     jobType.setWorkTypeName("最终交互作业");
                 }
                 list1.add(jobType);
             }
         }
        return Result.ok().data(list1);
    }
    /*选择小组*/
    @Override
    public Result<RestGroup> SelectGroup(Integer id) {
        if (id==null ||id==0){
            return Result.error().message("请选择课程");
        }
        List<RestGroup> list =teacherTaskMapper.RestGroup(id);
        return Result.ok().data(list);
    }
    /*查询学生*/
    @Override
    public Result<RestStudent> SelectStudents(Integer id, Integer teamId) {
        List<RestStudent> list =teacherTaskMapper.SelectStudents(id,teamId);
        return Result.ok().data(list);
    }
}
